package com.dmall.modules.admin.service.impl;

import com.dmall.common.utils.Result;
import com.dmall.modules.admin.entity.AdminUserToken;
import com.dmall.modules.admin.mapper.AdminUserTokenMapper;
import com.dmall.modules.admin.oauth2.TokenGenerator;
import com.dmall.modules.admin.service.AdminUserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Chen 2017/12/7
 */
@Service
public class AdminUserTokenServiceImpl implements AdminUserTokenService{
    @Autowired
    private AdminUserTokenMapper adminUserTokenMapper;
    //12小时后过期
    private final static int EXPIRE = 3600 * 12;
    /**
     * 根据用户ID创建token
     * @param userId
     * @return
     */
    @Override
    public Result createToken(Long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();
        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime()+ EXPIRE*1000);
        //判断是否生成过token
        AdminUserToken adminUserToken = findTokenByUserId(userId);
        if(adminUserToken == null){
            adminUserToken = new AdminUserToken();
            adminUserToken.setUserId(userId);
            adminUserToken.setToken(token);
            adminUserToken.setUpdateTime(now);
            adminUserToken.setExpireTime(expireTime);
            adminUserTokenMapper.insert(adminUserToken);
        }else {
            adminUserToken.setToken(token);
            adminUserToken.setUpdateTime(now);
            adminUserToken.setExpireTime(expireTime);
            adminUserTokenMapper.updateByPrimaryKey(adminUserToken);
        }
        return Result.ok().put("token", token).put("expire", EXPIRE);
    }

    /**
     * 根据用户Id查询是否生成了Token
     * @param userId
     * @return
     */
    @Override
    public AdminUserToken findTokenByUserId(Long userId) {
        return adminUserTokenMapper.selectByPrimaryKey(userId);
    }
}
